package com.younion.action.manage;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.younion.business.ICustomerService;
import com.younion.business.IWebFileService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.SysConstants;
import com.younion.common.paginator.Paginator;
import com.younion.common.util.ImageFileUtil;
import com.younion.vo.CustomerVO;
import com.younion.vo.WebFileVO;

import cpcns.jhsks.util.MapCollectionUtils;

public class WebManagerAction extends BaseAction {
	
	private static final long serialVersionUID = 9223058909151627905L;

	protected static final Log logger = LogFactory.getLog(WebManagerAction.class);
	
	private IWebFileService webFileService = null;
	
	@Autowired
	private ICustomerService customerService = null;
	
	private WebFileVO webFileVO = new WebFileVO();
	
	private List<WebFileVO> webFileList;
	
	private String ids;
	
	/**
	 * 列表：翻页区；数据区
	 */
	@SuppressWarnings("unchecked")
	public String listPic() {
		Integer type = Integer.parseInt(request.getParameter("type"));
		try {
			Map paramMap = new HashMap();
			paramMap.put("type", type);
			// 获取总记录数
			int total = this.webFileService.selectCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);
			this.webFileList = this.webFileService.selectForPage(paramMap, paginator);
			// 保存分页对象
			this.savaPaginator(paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (type == 0)
			return SUCCESS;
		else
			return "fileList";
	}
	
	/**
	 * 新增
	 */
	public String addPic() {
		return SUCCESS;
	}
	
	/**
	 * 保存动作
	 */
	public String savePic() {
		String removePic = request.getParameter("removePics");
		try {
			if (this.webFileVO.getTop() == 1) {
				this.webFileVO.setTop(this.webFileService.selectMaxTop() + 1);
			} else if (this.webFileVO.getId() != null) {
				this.webFileVO.setTop(null);
			}
			if (this.webFileVO.getId() == null) {
				this.webFileVO.setId(this.webFileService.insertByVo(this.webFileVO));
			} else {
				Map paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(this.webFileVO));
				this.webFileService.updateWebFileByMap(paramMap);
			}
			String realPath = request.getSession().getServletContext().getRealPath(SysConstants.IMG_PATH);
			File tempFile = new File(realPath + File.separator + "webIndexPic" + File.separator + "temp");
			File realFile = new File(realPath + File.separator + "webIndexPic" + File.separator + this.webFileVO.getId());
			String oldPic = request.getParameter("oldPic");
			//修改
			if (oldPic != null && !oldPic.equals("")) {
				if (!oldPic.equals(this.webFileVO.getFileName())) {
					ImageFileUtil.copyImage(tempFile, realFile, this.webFileVO.getFileName());
					ImageFileUtil.deleteImage(realFile, oldPic, false);
				}
			}
			//添加
			else {
				ImageFileUtil.copyImage(tempFile, realFile, this.webFileVO.getFileName());
			}
			ImageFileUtil.deleteImage(tempFile, removePic, false);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		request.setAttribute("refreshNavTabId", "listPic");
		return SUCCESS;
	}
	
	/**
	 * 保存动作
	 */
	@SuppressWarnings("unchecked")
	public String saveFile() {
		String removePic = request.getParameter("removePics");
		try {
			Map paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(this.webFileVO));
			if (this.webFileVO.getFileName() == null || this.webFileVO.getFileName().equals(""))
				paramMap.put("fileName", null);
			if (this.webFileVO.getLinkFile() == null || this.webFileVO.getLinkFile().equals(""))
				paramMap.put("linkFile", null);
			this.webFileService.updateWebFileByMap(paramMap);
			String realPath = request.getSession().getServletContext().getRealPath(SysConstants.IMG_PATH);
			File tempFile = new File(realPath + File.separator + "webIndexFile" + File.separator + "temp");
			File realFile = new File(realPath + File.separator + "webIndexFile" + File.separator + this.webFileVO.getId());
			String oldPic = request.getParameter("oldPic");
			//修改
			if (oldPic != null && !oldPic.equals("")) {
				ImageFileUtil.deleteImage(realFile, oldPic, false);
			}
			ImageFileUtil.copyImage(tempFile, realFile, this.webFileVO.getFileName());
			ImageFileUtil.deleteImage(tempFile, removePic, false);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		request.setAttribute("refreshNavTabId", "listFile");
		return SUCCESS;
	}
	
	/**
	 *修改保存，调度Jsp
	 */
	public String editPic() {
		try {
			this.webFileVO = this.webFileService.selectWebFileById(this.webFileVO.getId());
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (this.webFileVO.getType() == 0)
			return SUCCESS;
		else
			return "fileEdit";
	}
	
	/**
	 * 删除
	 */
	public String deletePic() {
		String realPath = request.getSession().getServletContext().getRealPath(SysConstants.IMG_PATH + "webIndexPic" + File.separator);
		File file = new File(realPath);
		try {
			WebFileVO vo = this.webFileService.selectWebFileById(this.webFileVO.getId());
			this.webFileService.deleteWebFileById(this.webFileVO.getId());
			File toFile = new File(file, String.valueOf(this.webFileVO.getId()));
			ImageFileUtil.deleteImage(toFile, vo.getFileName(), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		request.setAttribute("refreshNavTabId", "listPic");
		return SUCCESS;
	}
	
	/**
	 * 批量删除
	 */
	public String deletePics() {
		String realPath = request.getSession().getServletContext().getRealPath(SysConstants.IMG_PATH + "webIndexPic" + File.separator);
		List list = Arrays.asList(this.ids.split(","));
		File file = new File(realPath);
		try {
			List<WebFileVO> listVo = this.webFileService.selectByIds(list);
			for (WebFileVO vo : listVo) {
				File toFile = new File(file, String.valueOf(vo.getId()));
				ImageFileUtil.deleteImage(toFile, vo.getFileName(), true);
			}
			this.webFileService.deleteWebFileByIds(list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		request.setAttribute("refreshNavTabId", "listPic");
		return SUCCESS;
	}
	
	public String updateTopPic() {
		try {
			Map<String, Integer> map = new HashMap<String, Integer>();
			map.put("id", this.webFileVO.getId());
			Integer maxTop = this.webFileService.selectMaxTop();
			map.put("maxTop", maxTop + 1);
			this.webFileService.updateTopById(map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		request.setAttribute("refreshNavTabId", "listPic");
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String index() {
		Map paramMap = new HashMap();
		paramMap.put("type", 0);
		try {
			int total = this.webFileService.selectCountByMap(paramMap);
			Paginator paginator = this.getPaginator(total);
			paginator.setPageSize(total);
			this.webFileList = this.webFileService.selectForPage(paramMap, paginator);
			request.setAttribute("picList", this.webFileList);

			paramMap = new HashMap();
			paramMap.put("type", 1);
			total = this.webFileService.selectCountByMap(paramMap);
			paginator = this.getPaginator(total);
			paginator.setPageSize(total);
			this.webFileList = this.webFileService.selectForPage(paramMap, paginator);
			request.setAttribute("fileList", this.webFileList);
			
			paginator = this.getPaginator(this.customerService.getCountByMap(null));
			paginator.setPageSize(4);
			request.setAttribute("customerList", this.customerService.get(null, paginator));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}
	
	public String customerList() {
		String temp = request.getParameter("page");
		Integer page = 1;
		if (temp != null && !temp.trim().equals("")) {
			try {
				page = Integer.parseInt(temp);
			} catch (Exception ex) {
				page = 1;
			}
		}
		try {
			int total = this.customerService.getCountByMap(null);
			Paginator paginator = this.getPaginator(total);
			paginator.setPageIndex(page);
			paginator.setPageSize(20);
			request.setAttribute("customerList", this.customerService.get(null, paginator));
			this.savaPaginator(paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}
	
	public String getCustomer() {
		String id = request.getParameter("id");
		try {
			CustomerVO customer = this.customerService.getById(id);
			response.setContentType("text/xml; charset=utf-8");
			PrintWriter out = response.getWriter();
			response.setHeader("Cache-Control", "no-cache");
			out.println("<?xml version='1.0' encoding='utf-8'?>");
			out.println("<Results><Result>");
			out.println("<ID>"+customer.getId()+"</ID>");
			out.println("<PicName><![CDATA["+customer.getPicName()+"]]></PicName>");
			out.println("<Introduce><![CDATA["+customer.getIntroduce()+"]]></Introduce>");
			out.println("<MemberBenefits><![CDATA["+customer.getMemberBenefits()+"]]></MemberBenefits>");
			out.println("</Result></Results>");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}
	
	public void setWebFileService(IWebFileService webFileService) {
		this.webFileService = webFileService;
	}
	
	public List<WebFileVO> getWebFileList() {
		return this.webFileList;
	}

	public WebFileVO getWebFileVO() {
		return webFileVO;
	}

	public void setWebFileVO(WebFileVO webFileVO) {
		this.webFileVO = webFileVO;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

}
